package com.qiezi.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;


import com.qiezi.App;
import com.qiezi.R;
import com.qiezi.mvp.BaseMvpView;
import com.qiezi.mvp.BasePresenter;
import com.qiezi.mvp.PresenterDispatch;
import com.qiezi.mvp.PresenterProviders;
import com.qiezi.util.StatusBarUtil;
import com.qiezi.util.Util;

import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;


public abstract class BaseMvpActivity<P extends BasePresenter> extends AppCompatActivity implements BaseMvpView {


    private PresenterDispatch mPresenterDispatch;
    private PresenterProviders mPresenterProviders;

    public void complete() {
    }

    protected abstract int getLayoutRes();

    protected P getPresenter() {
        return this.mPresenterProviders.getPresenter(0);
    }

    public PresenterProviders getPresenterProviders() {
        return this.mPresenterProviders;
    }

    protected abstract void initData(Bundle saveBundle);

    protected abstract void initListener();

    public void setFitsSystemWindows() {
        ViewGroup contentFrameLayout = findViewById(android.R.id.content);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null && Build.VERSION.SDK_INT >= 14) {
            parentView.setFitsSystemWindows(true);
        }
    }
    protected void onCreate(Bundle saveBundle) {
        super.onCreate(saveBundle);
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
        Util.setCustomDensity(this, App.getInstance());
        StatusBarUtil.StatusBarLightMode(this);


//        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        setContentView(getLayoutRes());
        setFitsSystemWindows();
        ButterKnife.bind(this);
        this.mPresenterProviders = PresenterProviders.inject(this);
        this.mPresenterDispatch = new PresenterDispatch(this.mPresenterProviders);
        this.mPresenterDispatch.attachView(this, this);
        this.mPresenterDispatch.onCreatePresenter(saveBundle);
        initData(saveBundle);
        initListener();
    }


    protected boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }

    protected void onDestroy() {
        super.onDestroy();
        this.mPresenterDispatch.detachView();
    }

    protected void onSaveInstanceState(Bundle paramBundle) {
        super.onSaveInstanceState(paramBundle);
        this.mPresenterDispatch.onSaveInstanceState(paramBundle);
    }

    // 将dip值转换为px值
    public int dip2px(float dipValue){
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    // 将px值转换为dip或dp值
    public int px2dip(float pxValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    // 将px值转换为sp值
    public int px2sp(float pxValue) {
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    // 将sp值转换为px值
    public int sp2px(float spValue) {
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    public void showError(String msg) {
        if (msg == null || msg.length() == 0)return;
        toast(msg);
    }

    public void toast(String msg){
        Toasty.normal(this, msg).show();
    }

    public void showProgressUI(boolean paramBoolean) {
    }

    public void showProgressUI(String hint) {

    }

    public void log(Object log){
        StringBuilder methodName = new StringBuilder();
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement s : stackTrace){
            String name = s.getClassName();
            int last = name.indexOf("$");
            if (last > 0){
                name = name.substring(0,last);
            };
            if (name.equals(this.getClass().getName())) {
                methodName.append(s.getClassName())
                        .append(".")
                        .append(s.getMethodName())
                        .append(" 第")
                        .append(s.getLineNumber())
                        .append("行");
                break;
            }
        }
        System.out.println(methodName.toString()+" : "+log);
    }

    public void finish(int resultCode) {
        setResult(resultCode);
        finish();
    }

    public void finish(int resultCode, Intent data){
        setResult(resultCode,data);
        finish();
    }

    @Override
    public void finish() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null) manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        super.finish();
    }
}

